﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Web.Common;

namespace Web.Filters
{
    public class ApiAuthentication : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var attr = actionContext.ActionDescriptor
                .GetCustomAttributes<AllowAnonymousAttribute>()
                .OfType<AllowAnonymousAttribute>();

            bool isAnonymous = attr.Any(a => a is AllowAnonymousAttribute);

            if (isAnonymous)
            {
                base.OnActionExecuting(actionContext);
            }
            else
            {
                string token = string.Empty;

                if (actionContext.Request.Headers.Contains("Token"))
                    token = HttpUtility.UrlDecode(actionContext.Request.Headers.GetValues("Token").FirstOrDefault());
                if (!string.IsNullOrEmpty(token))
                {
                    if (ValidateToken(token))
                        base.OnActionExecuting(actionContext);
                    else
                        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                }
                else
                {
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                }
            }
        }

        public virtual bool ValidateToken(string token)
        {
            token = token.Replace(' ', '+');
            string tRealitytoken = "";
            try
            {
                tRealitytoken = BaseWebApiExt.GetRealityToken(token);//解密
                //log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType).Info("解密后："+tRealitytoken);
            }
            catch (Exception)
            {
                return false;
            }

            //验证内存中是否存在
            if (BaseWebApiExt.DicToken != null && BaseWebApiExt.DicToken.Count() > 0)
            {
                if (BaseWebApiExt.DicToken.ContainsValue(tRealitytoken))
                {
                    return true;
                }
            }
            //验证数据库是否存在
            if (Convert.ToInt32(FreeADO.DBUtility.DbHelperSQL.GetSingle("select Count(*) from Users where Token='"+tRealitytoken+"' and IsDeleted=0"))>0)
            {
                return true;
            }
            else
            {
                return false;
            }
            //base64的字符串
            //字符串会转成一个byte[]
            //结构是 uid + uname + token串
            //去数据库中验证，合法后，刷新token，返回给客户，并且保存到数据库
        }

    }
}